const express = require('express');
const router = express.Router();
const { ChapterHighlights, User } = require('../models');
const { authenticateToken, requireRole } = require('../middleware/auth');
const { Op } = require('sequelize');

// 获取最大章节号
router.get('/max-chapter-number', async (req, res) => {
  try {
    const maxChapter = await ChapterHighlights.max('chapterNumber');
    const nextChapterNumber = (maxChapter || 0) + 1;
    
    res.json({
      success: true,
      data: {
        maxChapterNumber: maxChapter || 0,
        nextChapterNumber
      }
    });
  } catch (error) {
    console.error('获取最大章节号失败:', error);
    res.status(500).json({
      success: false,
      message: '获取最大章节号失败',
      error: error.message
    });
  }
});


// 获取所有章节要点配置（支持分页和筛选）
router.get('/', async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      chapterNumber,
      isActive,
      search
    } = req.query;

    const offset = (page - 1) * limit;
    const where = {};

    // 筛选条件
    if (chapterNumber) {
      where.chapterNumber = chapterNumber;
    }

    if (isActive !== undefined) {
      where.isActive = isActive === 'true';
    }

    if (search) {
      where[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { 'leftSection.title': { [Op.like]: `%${search}%` } },
        { 'rightSection.title': { [Op.like]: `%${search}%` } }
      ];
    }

    const { count, rows } = await ChapterHighlights.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'email']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'email']
        }
      ],
      order: [['sortOrder', 'ASC'], ['chapterNumber', 'ASC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    res.json({
      success: true,
      data: rows,
      pagination: {
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取章节要点配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取章节要点配置失败',
      error: error.message
    });
  }
});

// 根据ID获取单个章节要点配置
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const chapterHighlights = await ChapterHighlights.findByPk(id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'email']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'email']
        }
      ]
    });

    if (!chapterHighlights) {
      return res.status(404).json({
        success: false,
        message: '章节要点配置不存在'
      });
    }

    res.json({
      success: true,
      data: chapterHighlights
    });
  } catch (error) {
    console.error('获取章节要点配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取章节要点配置失败',
      error: error.message
    });
  }
});

// 根据章节号获取章节要点配置
router.get('/chapter/:chapterNumber', async (req, res) => {
  try {
    const { chapterNumber } = req.params;

    const chapterHighlights = await ChapterHighlights.findOne({
      where: {
        chapterNumber: parseInt(chapterNumber),
        isActive: true
      },
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'email']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'email']
        }
      ]
    });

    if (!chapterHighlights) {
      return res.status(404).json({
        success: false,
        message: '章节要点配置不存在或未启用'
      });
    }

    res.json({
      success: true,
      data: chapterHighlights
    });
  } catch (error) {
    console.error('获取章节要点配置失败:', error);
    res.status(500).json({
      success: false,
      message: '获取章节要点配置失败',
      error: error.message
    });
  }
});

// 创建章节要点配置（需要管理员或教师权限）
router.post('/', authenticateToken, requireRole(['admin', 'teacher']), async (req, res) => {
  try {
    const {
      chapterNumber,
      title,
      leftSection,
      rightSection,
      tip,
      isActive = true,
      sortOrder = 0
    } = req.body;

    // 检查章节号是否已存在
    const existingChapter = await ChapterHighlights.findOne({
      where: { chapterNumber }
    });

    if (existingChapter) {
      return res.status(400).json({
        success: false,
        message: `章节 ${chapterNumber} 的要点配置已存在`
      });
    }

    // 验证必需字段
    if (!chapterNumber || !title) {
      return res.status(400).json({
        success: false,
        message: '章节号和标题为必填字段'
      });
    }

    const chapterHighlights = await ChapterHighlights.create({
      chapterNumber,
      title,
      leftSection: leftSection || {
        title: '',
        icon: 'lightning',
        subsections: []
      },
      rightSection: rightSection || {
        title: '',
        icon: 'book',
        subsections: []
      },
      tip: tip || {
        label: '学习建议',
        content: ''
      },
      isActive,
      sortOrder,
      createdBy: req.user.id,
      updatedBy: req.user.id
    });

    // 获取完整的创建结果
    const result = await ChapterHighlights.findByPk(chapterHighlights.id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'email']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'email']
        }
      ]
    });

    res.status(201).json({
      success: true,
      message: '章节要点配置创建成功',
      data: result
    });
  } catch (error) {
    console.error('创建章节要点配置失败:', error);
    res.status(500).json({
      success: false,
      message: '创建章节要点配置失败',
      error: error.message
    });
  }
});

// 更新章节要点配置（需要管理员或教师权限）
router.put('/:id', authenticateToken, requireRole(['admin', 'teacher']), async (req, res) => {
  try {
    const { id } = req.params;
    const {
      chapterNumber,
      title,
      leftSection,
      rightSection,
      tip,
      isActive,
      sortOrder
    } = req.body;

    const chapterHighlights = await ChapterHighlights.findByPk(id);

    if (!chapterHighlights) {
      return res.status(404).json({
        success: false,
        message: '章节要点配置不存在'
      });
    }

    // 如果更新章节号，检查是否与其他记录冲突
    if (chapterNumber && chapterNumber !== chapterHighlights.chapterNumber) {
      const existingChapter = await ChapterHighlights.findOne({
        where: {
          chapterNumber,
          id: { [Op.ne]: id }
        }
      });

      if (existingChapter) {
        return res.status(400).json({
          success: false,
          message: `章节 ${chapterNumber} 的要点配置已存在`
        });
      }
    }

    // 更新字段
    const updateData = {
      updatedBy: req.user.id
    };

    if (chapterNumber !== undefined) updateData.chapterNumber = chapterNumber;
    if (title !== undefined) updateData.title = title;
    if (leftSection !== undefined) updateData.leftSection = leftSection;
    if (rightSection !== undefined) updateData.rightSection = rightSection;
    if (tip !== undefined) updateData.tip = tip;
    if (isActive !== undefined) updateData.isActive = isActive;
    if (sortOrder !== undefined) updateData.sortOrder = sortOrder;

    await chapterHighlights.update(updateData);

    // 获取更新后的完整数据
    const result = await ChapterHighlights.findByPk(id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'email']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'email']
        }
      ]
    });

    res.json({
      success: true,
      message: '章节要点配置更新成功',
      data: result
    });
  } catch (error) {
    console.error('更新章节要点配置失败:', error);
    res.status(500).json({
      success: false,
      message: '更新章节要点配置失败',
      error: error.message
    });
  }
});

// 删除章节要点配置（需要管理员权限）
router.delete('/:id', authenticateToken, requireRole(['admin']), async (req, res) => {
  try {
    const { id } = req.params;

    const chapterHighlights = await ChapterHighlights.findByPk(id);

    if (!chapterHighlights) {
      return res.status(404).json({
        success: false,
        message: '章节要点配置不存在'
      });
    }

    await chapterHighlights.destroy();

    res.json({
      success: true,
      message: '章节要点配置删除成功'
    });
  } catch (error) {
    console.error('删除章节要点配置失败:', error);
    res.status(500).json({
      success: false,
      message: '删除章节要点配置失败',
      error: error.message
    });
  }
});

// 批量更新排序
router.put('/batch/sort', authenticateToken, requireRole(['admin', 'teacher']), async (req, res) => {
  try {
    const { items } = req.body; // [{ id, sortOrder }, ...]

    if (!Array.isArray(items)) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的排序数据'
      });
    }

    // 批量更新排序
    const updatePromises = items.map(item => 
      ChapterHighlights.update(
        { 
          sortOrder: item.sortOrder,
          updatedBy: req.user.id
        },
        { where: { id: item.id } }
      )
    );

    await Promise.all(updatePromises);

    res.json({
      success: true,
      message: '排序更新成功'
    });
  } catch (error) {
    console.error('批量更新排序失败:', error);
    res.status(500).json({
      success: false,
      message: '批量更新排序失败',
      error: error.message
    });
  }
});

// 批量启用/禁用
router.put('/batch/toggle', authenticateToken, requireRole(['admin', 'teacher']), async (req, res) => {
  try {
    const { ids, isActive } = req.body;

    if (!Array.isArray(ids) || typeof isActive !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: '请提供有效的ID列表和状态'
      });
    }

    await ChapterHighlights.update(
      { 
        isActive,
        updatedBy: req.user.id
      },
      { where: { id: { [Op.in]: ids } } }
    );

    res.json({
      success: true,
      message: `批量${isActive ? '启用' : '禁用'}成功`
    });
  } catch (error) {
    console.error('批量状态更新失败:', error);
    res.status(500).json({
      success: false,
      message: '批量状态更新失败',
      error: error.message
    });
  }
});

module.exports = router;